package com.ruoyi.patrol.service.impl;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.patrol.domain.PatrolPath;
import com.ruoyi.patrol.mapper.PatrolPathMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.patrol.mapper.PatrolPointMapper;
import com.ruoyi.patrol.domain.PatrolPoint;
import com.ruoyi.patrol.service.IPatrolPointService;

/**
 * 巡查点位Service业务层处理
 * 
 * @author yepanpan
 * @date 2025-05-08
 */
@Service
public class PatrolPointServiceImpl implements IPatrolPointService 
{
    private static final Logger log = LoggerFactory.getLogger(PatrolPointServiceImpl.class);

    @Autowired
    private PatrolPointMapper patrolPointMapper;
    @Autowired
    private PatrolPathMapper patrolPathMapper;

    /**
     * 查询巡查点位
     * 
     * @param id 巡查点位主键
     * @return 巡查点位
     */
    @Override
    public PatrolPoint selectPatrolPointById(Long id)
    {
        return patrolPointMapper.selectPatrolPointById(id);
    }

    /**
     * 查询巡查点位列表
     * 
     * @param patrolPoint 巡查点位
     * @return 巡查点位
     */
    @Override
    public List<PatrolPoint> selectPatrolPointList(PatrolPoint patrolPoint)
    {
        return patrolPointMapper.selectPatrolPointList(patrolPoint);
    }

    /**
     * 新增巡查点位
     * 
     * @param patrolPoint 巡查点位
     * @return 结果
     */
    @Override
    public int insertPatrolPoint(PatrolPoint patrolPoint)
    {
        patrolPoint.setCreateTime(DateUtils.getNowDate());
        return patrolPointMapper.insertPatrolPoint(patrolPoint);
    }

    /**
     * 修改巡查点位
     * 
     * @param patrolPoint 巡查点位
     * @return 结果
     */
    @Override
    public int updatePatrolPoint(PatrolPoint patrolPoint)
    {
        patrolPoint.setUpdateTime(DateUtils.getNowDate());
        return patrolPointMapper.updatePatrolPoint(patrolPoint);
    }

    /**
     * 批量删除巡查点位
     * 
     * @param ids 需要删除的巡查点位主键
     * @return 结果
     */
    @Override
    public int deletePatrolPointByIds(Long[] ids)
    {
        return patrolPointMapper.deletePatrolPointByIds(ids);
    }

    /**
     * 删除巡查点位信息
     * 
     * @param id 巡查点位主键
     * @return 结果
     */
    @Override
    public int deletePatrolPointById(Long id)
    {
        return patrolPointMapper.deletePatrolPointById(id);
    }


    /**
     * 导入数据
     *
     * @param dataList 数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importData(List<PatrolPoint> dataList, Boolean isUpdateSupport, String operName){
        if (StringUtils.isNull(dataList) || dataList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        List<PatrolPath> pathList = patrolPathMapper.selectPatrolPathList(null);
        if(pathList == null || pathList.isEmpty()){
            throw new ServiceException("请先添加路径信息");
        }

        Map<String, Long> pathMap = pathList.stream().collect(Collectors.toMap(PatrolPath::getName, PatrolPath::getId));

        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        PatrolPoint pc = new PatrolPoint();
        for (PatrolPoint row : dataList)
        {
            try
            {
                if(StringUtils.isEmpty(row.getPathName())){
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、点位 " + row.getName() + " 所属路线不能为空");
                    continue;
                }
                Long pathId = pathMap.get(row.getPathName().trim());
                if(pathId == null){
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、路线 " + row.getPathName() + " 不存在");
                    continue;
                }
                row.setPathId(pathId);

                pc.setPathId(pathId);
                pc.setCode(row.getCode());
                // 验证是否存在旧数据
                List<PatrolPoint> old = patrolPointMapper.selectPatrolPointList(pc);
                if (StringUtils.isEmpty(old))
                {
                    row.setCreateBy(operName);
                    insertPatrolPoint(row);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、点位 " + row.getCode() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    row.setId(old.get(0).getId());
                    row.setUpdateBy(operName);
                    updatePatrolPoint(row);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、点位 " + row.getCode() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、点位 " + row.getCode() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、点位 " + row.getCode() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
